package com.secondmybatis.filter;

import com.secondmybatis.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Map;

//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 0.强转对象
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        // 1.获取请求url
        StringBuffer url = req.getRequestURL();   //获取完整的路径 例如：http://localhost:8080/login
        String uri = req.getRequestURI();         // 获取业务路径  例如： /login
        // 2.判断请求路径中是否包含Login,如果包含，说明是登录操作，放行
        if(uri.contains("login")){
            // 登录操作，放行
            filterChain.doFilter(servletRequest,servletResponse);
            // 一定要结束当前请求，不应该继续往下执行代码逻辑
            return ;
        }
        // 3.获取请求头中的令牌
        String token = req.getHeader("token");
        // 4.判断令牌是否存在，如果不存在，则响应401
        if(token==null){
            rep.setStatus(401);
            return ;
//            throw new BusinessException("未登录，请登录");
        }
        // 5.解析token,如果解析失败，则响应401
        try{
            Map<String, Object> claims = JwtUtils.parseJwt(token);
        }catch (Exception e){
            rep.setStatus(401);
            return;
//            throw new BusinessException("未登录，请先登录");
        }

        // 6.放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
